﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataObjects;
using BusinessLayer;
namespace ControleCaixa
{
    public partial class cadFilial : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                EmpresaBL _empresaBl = new EmpresaBL();
                ddlEmpresa.DataSource = _empresaBl.Consultar();
                ddlEmpresa.DataBind();
                if (Session["filialId"] != null && Session["filialId"] != string.Empty)
                {
                    FilialBL _filialBl = new FilialBL();
                    List<Filial> listFilial = _filialBl.Consultar(int.Parse(Session["filialId"].ToString()));
                    if (listFilial.Count != 0)
                    {
                        txtFilial.Text = listFilial[0].Descricao;
                        txtEndereco.Text = listFilial[0].Endereco;
                        ddlAtivo.SelectedValue = listFilial[0].Ativo.ToString();
                        ddlEmpresa.SelectedValue = listFilial[0].EmpresaId.ToString();
                    }
                }

            }

        }

        protected void btnVoltar_Click(object sender, EventArgs e)
        {
            Session["filialId"] = null;
            Response.Redirect("viewFilial.aspx");
        }

        protected void btnPesquisa_Click(object sender, EventArgs e)
        {
            try
            {
                Filial _filial = new Filial();
                FilialBL _filialBL = new FilialBL();
                _filial.Descricao = txtFilial.Text;
                _filial.Endereco = txtEndereco.Text;
                _filial.Ativo = Convert.ToInt16(ddlAtivo.SelectedValue);
                _filial.EmpresaId = Convert.ToInt16(ddlEmpresa.SelectedValue);

                if (Session["filialId"] != null && Session["filialId"] != string.Empty)
                {
                    _filial.FilialId = int.Parse(Session["filialId"].ToString());
                    _filialBL.Alterar(_filial);
                    sucesso.InnerText = "Filial alterada com sucesso.";
                }
                else
                {
                    _filialBL.Inserir(_filial);
                    txtFilial.Text = string.Empty;
                    txtEndereco.Text = string.Empty;
                    sucesso.InnerText = "Empresa salva com sucesso.";
                }
            }
            catch (Exception ex)
            {
                mensagem.InnerText = ex.Message;
            }

        }
    }
}